﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FileDeleteNew
{
    public partial class Form1 : Form
    {
        string jsonPath = Application.StartupPath + "\\FileConfig.json";
        private UserControl1 userControl;
        //int fileNum = 1;
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            btn_Delete.Hide();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            //this.ShowInTaskbar = true;
            //int oldNum = ReadJsonFile();
            //fileNum = oldNum;
            ShowUserControl();
        }
        private void btn_Add_Click(object sender, EventArgs e)
        {
            userControl = new UserControl1();
            //userControl.Name = "UserControl" + fileNum;
            userControl.Width = 700;
            userControl.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
            flowLayoutPanel1.Controls.Add(userControl);
            //fileNum++;
        }
        private void btn_Delete_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("请确认是否删除当前选中信息？","Question",MessageBoxButtons.OKCancel,MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
                RemoveAllControls(this);
            }   
        }
        private void RemoveAllControls(Control container)
        {
            List<string> list = new List<string>();
            string txtLocation = "";
            // 反向遍历，以避免因删除控件导致索引错位的问题
            for (int i = container.Controls.Count - 1; i >= 0; i--)
            {
                Control control = container.Controls[i];
                if (control is UserControl1 userControl)
                {
                    // 检查用户控件内是否有CheckBox，并且是否被选中
                    CheckBox checkedCheckBox = userControl.Controls.OfType<CheckBox>()
                       .FirstOrDefault(cb => cb.Checked);
                    // 如果找到被选中的CheckBox，则删除整个用户控件
                    if (checkedCheckBox != null)
                    {
                        var textBoxes = control.Controls.OfType<TextBox>();
                        foreach (var textBox in textBoxes)
                        {
                            txtLocation = textBox.Text;
                        }
                        string jsonStr = File.ReadAllText(jsonPath);

                        List<FileClass> dataObjects = JsonConvert.DeserializeObject<List<FileClass>>(jsonStr);

                        FileClass fileClass = dataObjects.Find(x => x.FileLocation == txtLocation);
                        if (fileClass != null)
                        {
                            dataObjects.Remove(fileClass);
                            jsonStr = JsonConvert.SerializeObject(dataObjects, Formatting.Indented);
                            File.WriteAllText(jsonPath, jsonStr);
                            container.Controls.Remove(userControl);
                            // 可能还需要处理用户控件的释放或事件解绑
                            userControl.Dispose(); // 如果确定不再需要这个控件的实例，可以调用Dispose
                        }
                        else
                        {
                            container.Controls.Remove(userControl);
                            // 可能还需要处理用户控件的释放或事件解绑
                            userControl.Dispose(); // 如果确定不再需要这个控件的实例，可以调用Dispose
                        }

                    }
                }
                // 如果控件本身是一个容器，递归检查它内部的控件
                else if (control.HasChildren)
                {
                    RemoveAllControls(control);
                }
            }
        }
        /// <summary>
        /// 删除后自动更新Json文件ID和UI界面
        /// </summary>
        /// <param name="container"></param>
        private void RefreshIDControl(Control container)
        { 
            
        }
        private void ShowUserControl()
        {
            string jsonStr = File.ReadAllText(jsonPath);
            // 假设JSON是一个对象数组，每个对象都有"DisplayName"属性
            List<FileClass> dataObjects = JsonConvert.DeserializeObject<List<FileClass>>(jsonStr);

            // 遍历数据对象，为每个对象创建一个UserControl实例并添加到父控件中
            foreach (var dataObject in dataObjects)
            {
                UserControl1 userControl = new UserControl1();
                userControl.TextLblValue = dataObject.FileID;
                userControl.TextFileLocationValue = dataObject.FileLocation;
                userControl.TextDelTimeValue = dataObject.FileDelTime;
                userControl.SelectState = false;
                //userControl.DelTimeState = false;
                userControl.DelState = true;
                userControl.Width = 700;
                userControl.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
                flowLayoutPanel1.Controls.Add(userControl); // 将用户控件添加到父控件中
            }
        }
        public int ReadJsonFile()
        {
            //读取json
            
            if (!File.Exists(jsonPath))
            {
                FileStream fs = File.Create(jsonPath);
            }
            JsonStore json = new JsonStore();
            json.StorePath = jsonPath;
            List<FileClass> datas;
            datas = json.ReadJson<FileClass>();   //读取多少个数据
            return datas.Count;
        }
    }
}
